//登录与注册模块
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api"
import {getToken, setToken,removeToken} from "@/utils/token"
const state = {
    code: '',
    token: getToken(),
    userInfo:{}
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo 
    },
    //清除本地数据
    CLEAR(state){
        state.token = '',
        state.userInfo={},
        removeToken
    }
}
const actions = {
    //获取验证码,一般是由后端发给用户手机，但因为学习只能出此下策（没钱）
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODE", result.data)
            return "ok"
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result == 200) {
            return "ok"
        } else if (result.code == 223) {
            return Promise.reject(new Error('该手机号已被注册'))
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //登录业务
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        //服务器下发的token，用户的唯一标识
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            //持久化存储token
            setToken(result.data.token)
            return "ok"
        } else {
            return Promise.reject(new Error("用户或密码不正确"))
        }
    },
    //获取用户信息
    async getUserInfo({ commit}) {
        let result = await reqUserInfo();
        if (result.code == 200) {
             commit('GETUSERINFO', result.data);
             return 'ok';
        } else {
             return Promise.reject(new Error('faile'));
        }
   },
   //退出登录
   async userLogout({commit}){
    //向服务器发请求，通知删除token
    let result = await reqLogout()
    //action里不能操作state，提交mutations修改state
    if(result.code == 200){
        commit("CLEAR")
        return "ok"
    }else{
        return Promise.reject(new Error('faile'))
    }
   }
}
const getters = {

}
export default {
    state,
    mutations,
    actions,
    getters
}